﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxEditors;
using Dez;

public partial class Default2 : System.Web.UI.Page
{
    string dfSelect;
    DEZ context = new DEZ();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetBtnVisible();
            //
            Label1.Text = Profile.UserInfo.disp.Kontragent.ToString();
            //
            dfSelect = ds_WorkList.SelectCommand;
            ASPxWebControl.RegisterBaseScript(this);
            var column = ((DevExpress.Web.ASPxGridView.GridViewDataComboBoxColumn)grd1.Columns["Kontragrnt"]);
            if (Profile.UserInfo.KontragentType == 1)
            {
                cbb_kontr.Value = Profile.UserInfo.ActiveKontragent;
                cbb_kontr.Enabled = false;
                //скрываем контрагента из списка
                column.EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.False;
                column.ReadOnly = true;
            }
            else
            {
                cbb_kontr.ReadOnly = false;
                column.EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.True;
            }
        }
    }

    protected void SetBtnVisible()
    {
        //btn_add.Enabled = grd1.VisibleRowCount > 1;
        btn_edit.Enabled = grd1.VisibleRowCount > 1;
        btn_delete.Enabled = grd1.VisibleRowCount > 1;
    }

    protected void btn_Exec_Click(object sender, EventArgs e)
    {
        ds_WorkList.SelectParameters.Clear();
        ds_WorkList.SelectParameters.Add("d1", dt1.Date.ToShortDateString());
        ds_WorkList.SelectParameters.Add("d2", dt2.Date.ToShortDateString());
        ds_WorkList.SelectParameters.Add("kontr", cbb_kontr.Value.ToString());

        grd1.DataSourceID = "ds_WorkList";

        grd1.DataBind();
        SetBtnVisible();
    }

    string selCom = "SELECT distinct(wl.CODE), " +
                       "wl.DATA, " +
                       "wl.KONTRAGENT,k.name KontrName, " +
                       "s.code Street, s.name streetname, " +
                       "wl.HOUSE, h.nomer, h.du, d.name DUName," +
                       "mh.worker,(p.f||' '||p.i||' '||p.o) fio, " +
                       "wl.NOTE " +
                       "FROM WORKLIST wl " +
                       "left outer join house h on h.code = wl.house " +
                       "left outer join street s on s.code = h.street " +
                       "left outer join KONTRAGENT k on k.code=wl.KONTRAGENT " +
                       "left outer join du d on d.code=h.du " +
                       "left outer join mhouse mh on mh.house=wl.house and mh.kontragent=wl.kontragent " +
                       "left outer join worker w on w.code=mh.worker " +
                       "left outer join piple p on p.code=w.piple";
    string updCom = "UPDATE WORKLIST " +
                    "SET " +
                    "    DATA = :DATA, " +
                    "    KONTRAGENT = :KONTRAGENT, " +
                    "    HOUSE = :HOUSE, " +
                    "    NOTE = :NOTE " +
                    "WHERE " +
                    "    CODE = :OLD_CODE";
    string delCom = "DELETE FROM WORKLIST WHERE CODE = :OLD_CODE";
    string insCom = "INSERT INTO WORKLIST( " +
                    "    CODE, " +
                    "    DATA, " +
                    "    KONTRAGENT, " +
                    "    HOUSE, " +
                    "    NOTE) " +
                    "VALUES( " +
                    "    :CODE, " +
                    "    :DATA, " +
                    "    :KONTRAGENT, " +
                    "    :HOUSE, " +
                    "    :NOTE)";

    protected void btn_edit_Click(object sender, EventArgs e)
    {
        grd1.StartEdit(grd1.FocusedRowIndex);
    }
    protected void ASPxButton1_Click(object sender, EventArgs e)
    {
        grd1.StartEdit(grd1.FocusedRowIndex);
    }
    protected void btn_add_Click(object sender, EventArgs e)
    {
        grd1.AddNewRow();
    }
    protected void btn_delete_Click(object sender, EventArgs e)
    {

    }

    protected void cbb_house_Init(object sender, EventArgs e)
    {
        ASPxComboBox cbb_house = (ASPxComboBox)sender;
        //GridViewDataItemTemplateContainer templateContainer = (GridViewDataItemTemplateContainer)cmbChild.NamingContainer;
        //cmbChild.ClientInstanceName = string.Format("cmbChild_{0}", templateContainer.VisibleIndex);
        cbb_house.Callback += new DevExpress.Web.ASPxClasses.CallbackEventHandlerBase(cbb_house_Callback);
    }

    void cbb_house_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        ASPxComboBox cbb_house = (ASPxComboBox)sender;
        // AccessDataSource cmbChildAccessDataSource = (AccessDataSource)cmbChild.NamingContainer.FindControl("asdChild");
        ds_house.SelectParameters[0].DefaultValue = e.Parameter;
        cbb_house.DataBindItems();
    }
    protected void grd1_CellEditorInitialize(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs e)
    {
        if (e.Column.FieldName == "HOUSE")
        {
            var combo = (ASPxComboBox)e.Editor;
            combo.Callback += new CallbackEventHandlerBase(combo_Callback);

            var grid = e.Column.Grid;
            if (!combo.IsCallback)
            {
                var countryID = -1;
                if (!grid.IsNewRowEditing)
                    countryID = (int)grid.GetRowValues(e.VisibleIndex, "STREET");
                FillCitiesComboBox(combo, countryID);
            }
        }
        if (e.Column.FieldName == "KONTRAGENT")
        {
            var combo = (ASPxComboBox)e.Editor;
            var col = e.Column;

            //если подрядчик
            if (Profile.UserInfo.KontragentType == 1)
            {
                combo.Value = Profile.UserInfo.ActiveKontragent;
                //скрываем поле для редактирования KONTRAGENT из формы редактирования
                col.EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.False;
            } //иначе (если дез)
            else
            {
                combo.Value = cbb_kontr.Value;
                combo.Enabled = true;
                //combo.ReadOnly = true;
                col.EditFormSettings.Visible = DevExpress.Utils.DefaultBoolean.True;
            }
        }
    }

    private void combo_Callback(object sender, CallbackEventArgsBase e)
    {
        var countryID = -1;
        Int32.TryParse(e.Parameter, out countryID);
        FillCitiesComboBox(sender as ASPxComboBox, countryID);
    }

    protected void FillCitiesComboBox(ASPxComboBox combo, int countryID)
    {
        combo.DataSourceID = "ds_house";
        ds_house.SelectParameters["STREET"].DefaultValue = countryID.ToString();
        combo.DataBindItems();

        combo.Items.Insert(0, new ListEditItem("", null)); // Null Item
    }

    protected void ds_WorkList_Inserting(object sender, SqlDataSourceCommandEventArgs e)
    {
        //устанавливаем значения по умолчанию перед вставкой
        if (e.Command.Parameters["KONTRAGENT"].Value == DBNull.Value)
        {
            e.Command.Parameters["KONTRAGENT"].Value = Profile.UserInfo.ActiveKontragent;
        }
    }
    protected void ds_WorkList_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        //устанавливаем значения по умолчанию перед вставкой
        if (e.Command.Parameters["KONTRAGENT"].Value == DBNull.Value)
        {
            e.Command.Parameters["KONTRAGENT"].Value = Profile.UserInfo.ActiveKontragent;
        }
    }
}